import pygame
import math

import constants as c
import data
import bird
import sounds

class Turbine(pygame.sprite.Sprite):
    def __init__(self, x, y):
        ''' Creates a turbine head, given its x and y coordinates'''
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = data.load_image("turbine.png", -1)
        self.original = self.image
        self.rect.center = (x, y)

        self.center = self.rect.center
        self.time_count = 0

        self._spinning = True

    @property
    def output(self):
        if self._spinning:
            return c.TURBINE_kW
        return 0

    def update(self, time_diff):
        self.time_count = self.time_count + time_diff
        if self.time_count > 1000:
            self.time_count = self.time_count - 1000

        # now if the turbine not spinning don't rotate!
        if self._spinning:
            self.image = pygame.transform.rotate(self.original,
                (self.time_count/1000.0*360.0))
        else:
            self._elapsed += time_diff
            if self._elapsed > self._delay:
                self._spinning = True
                self._elapsed = 0

        self.rect = self.image.get_rect(center = self.center)
    def collide(self, other):
        'someone has hit us! if it was a bird, calc the momentum and stop.'
        if isinstance(other, bird.Bird):
            # momentum in kgm/s
            p = other.m * math.sqrt(other.velx**2 + other.vely**2)
            # time out of action surely is larger for higher momentum.
            self._delay = p * c.TURBINE_HITDELAY
            self._elapsed = 0
            self._spinning = False

            # I love doing this dirty hack!! try and stop me...
            other.kill()

            # now for my next trick.. play sounds.
            sounds.play_sfx('windmill_stop.wav')

